import os
import time
from random import choice, randint

import undetected_chromedriver.v2 as uc
from fake_useragent import UserAgent
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

from Console import console
from Settings import BROWSER_VER, STANDART_DELAY, TIME_TO_SOLVE_CAPTCHA


class ChromeBrowser:
    def _initBrowser(self,PROXY=None):
        options = webdriver.ChromeOptions()
        options.page_load_strategy = 'eager'
        options.add_argument("--disable-blink-features=AutomationControlled")
        options.add_argument("--disable-dev-shm-usage")
        options.add_argument("--no-sandbox")
        options.add_argument("--mute-audio")
        if PROXY:
            #тут должны быть проверки прокси причем невьебенные
            options.add_argument('--proxy-server=https://%s' % PROXY)
    
        return options
    
    def Bypasser(self,driver):
        if not driver.find_elements(value="button.btn.btn-primary.g-recaptcha", by=By.CSS_SELECTOR) and driver.title=="Just a moment...":
            console.warning("Cloudflare Anti-bot detected")
            #EC.visibility_of_element_located((By.ID, "cf-spinner-redirecting"))
            try:
                WebDriverWait(driver,timeout=60).until_not(EC.presence_of_element_located((By.ID, "cf-spinner-redirecting")),"cf-spinner-redirecting not")
            except Exception as e:
                pass
                # driver.quit()
                # raise e
            if (driver.title.find('Access denied')!=1 and driver.title.find("used Cloudflare to restrict access")!=-1):
                console.error("Cloudflare denied")
                driver.quit()
                raise Exception("Cloudflare denied")
            console.warning("Cloudflare Bypassed")
            time.sleep(6)
        time.sleep(1)
        if driver.title.find("Cloudflare")!=-1 and driver.find_elements(value="//div[@id='checkbox' and not(contains(@style,'display:none'))]",by=By.XPATH ):
                console.warning("Captcha detected.Try solve it manually")
                time.sleep(TIME_TO_SOLVE_CAPTCHA)
                if driver.find_elements(value="//div[@id='checkbox' and not(contains(@style,'display:none'))]",by=By.XPATH ) and driver.title.find("Cloudflare")!=-1:
                    driver.quit()
                    raise Exception("Captcha detected")
        time.sleep(1)
        els = self.driver.find_elements(value="button.btn.btn-primary.g-recaptcha", by=By.CSS_SELECTOR)
        if els:
                console.warning("Found doge-button")
                els[0].click()
                #ActionChains(self.driver).click(els[0]).perform()
                time.sleep(4)
        time.sleep(1)
        if driver.find_elements(value="g-recaptcha-response",by=By.ID)  or driver.find_elements(value="//div[@id='checkbox' and not(contains(@style,'display:none'))]",by=By.XPATH ):
                console.warning("Captcha detected.Try solve it manually")
                time.sleep(TIME_TO_SOLVE_CAPTCHA)
                if driver.find_elements(value="g-recaptcha-response",by=By.ID):
                    driver.quit()
                    raise Exception("Captcha detected")
    
    def getURL(self,url, delay=60, PROXY=None):
        console.info("---AD task---")
        try:
            self.driver = uc.Chrome(options=self._initBrowser(PROXY),version_main=BROWSER_VER)
        except Exception as e:
            raise Exception(f"Error while initializing Chrome\n"+e.message)
        print("1")
        self.driver.maximize_window()
        self.driver.set_page_load_timeout(30)
        self.driver.implicitly_wait(5)
        self.driver.get(url)
        self.driver.save_screenshot("photos/1.png")
        console.info(f'Tittle of tab:{self.driver.title}')
        try:
            self.Bypasser(self.driver)
        except Exception as e:
            raise e
        
        
        if self.driver.current_url.find("doge.click")!=-1 :           
            WebDriverWait(self.driver,timeout=60).until(EC.presence_of_element_located((By.CLASS_NAME, "timer")),"AD task:timer element wasnt found")
            #try:
            timer=self.driver.find_element(value="timer", by=By.CLASS_NAME)
            # except:
            #     self.driver.quit()
            #     raise Exception("Cant find timer")
            #//*[@id="headbar"]/div[1]/div[1]/h5
            
            if timer and timer.text.find("Please wait")!=-1:
                    
                    try:
                            time_of_end=int(timer.text[timer.text.find('wait')+4:timer.text.find("seconds")].strip())
                    except:
                            try:
                                time_of_end=int(timer.text[timer.text.find('wait')+4:timer.text.find("second")].strip())
                            except:
                                self.driver.quit()
                                raise ValueError("AD task:Cant read value of timer element")
                    console.info(f"Site with timer({time_of_end}s) detected")
                    while time_of_end!=0 or timer.text.find("Please wait")!=-1:
                        
                        timer.click()
                        try:
                            time_of_end=int(timer.text[timer.text.find('wait')+4:timer.text.find("seconds")].strip())
                        except:
                            try:
                                time_of_end=int(timer.text[timer.text.find('wait')+4:timer.text.find("second")].strip())
                            except:
                                time.sleep(2)
                                break
                        
            else:
                self.driver.quit()
                raise IndexError('error when finding timer')
        time.sleep(2)
        self.driver.quit()
     
     
        
    
    def getBotUrl(self, url, delay=60, PROXY=None):
        console.info("---BOT task---")
        try:
            self.driver = uc.Chrome(options=self._initBrowser(PROXY),version_main=BROWSER_VER)
        except Exception as e:
            raise Exception(f"Error while initializing Chrome\n"+e.message)
        print("1")
        self.driver.maximize_window()
        self.driver.set_page_load_timeout(30)
        self.driver.implicitly_wait(5)
        self.driver.get(url)
        self.driver.save_screenshot("photos/1.png")
        console.info(f'Tittle of tab:{self.driver.title}')
        try:
            self.Bypasser(self.driver)
        except Exception as e:
            raise e
        WebDriverWait(self.driver,timeout=60).until(EC.presence_of_element_located((By.CLASS_NAME, "tgme_logo")),"tgme_logo until")
        telegram_link =self.driver.find_elements(value="tgme_page_extra", by=By.CLASS_NAME)
        bot_name = self.driver.find_elements(value= "tgme_page_title", by=By.CLASS_NAME)
        tg_link, bt_name = None, None
        if telegram_link:
            tg_link = telegram_link[0].text
        if bot_name:
            bt_name = bot_name[0].text
        self.driver.quit()
        return [tg_link, bt_name]
        
    
    def getGroupUrl(self, url, delay=60, PROXY=None):
        console.info("---GROUP task---")
        try:
            self.driver = uc.Chrome(options=self._initBrowser(PROXY),version_main=BROWSER_VER)
        except Exception as e:
            raise Exception(f"Error while initializing Chrome\n"+e.message)
        print("1")
        self.driver.maximize_window()
        self.driver.set_page_load_timeout(30)
        self.driver.implicitly_wait(5)
        self.driver.get(url)
        self.driver.save_screenshot("photos/1.png")
        console.info(f'Tittle of tab:{self.driver.title}')
        try:
            self.Bypasser(self.driver)
        except Exception as e:
            raise e
        WebDriverWait(self.driver,timeout=60).until(EC.presence_of_element_located((By.CLASS_NAME, "tgme_logo")))
        channel_name = self.driver.find_elements(value="tgme_page_title", by=By.CLASS_NAME)
        channel_link = self.driver.find_elements(value="tgme_action_button_new", by= By.CLASS_NAME)
        channel_link_text, channel_name_text = None, None
        if channel_name:
            channel_name_text = channel_name[0].text
        if "Telegram: Contact" in self.driver.title:
            channel_link_text = self.driver.title
            channel_link_text = channel_link_text.replace("Telegram: Contact ", "")
        self.driver.quit()
        return [channel_name_text, channel_link_text]
        
        



browser=ChromeBrowser()
